package com.inke.box.net.minasocket;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.inke.box.net.minasocket.vo.InkeMessage;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

import butterknife.BindView;

/**
 * Created by Administrator on 2017/11/8.
 */

public class InkeServerSocketHanlder extends IoHandlerAdapter {

    private int count = 0;//链接数量

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
        LogUtils.e("新客户端链接");
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
        LogUtils.e("新客户端进入");
        count++;
        LogUtils.e("第"+count+"链接"+"_______ip "+session.getRemoteAddress());
        ToastUtils.showShort("服务器：新客户端进入"+session.getRemoteAddress());
//        session.write("hi clinet!");

        //存储session 客户端ip作为key
        SessionSendUtils.getIns().setSession(session);
    }

    /**
     * 接手消息
     * */
    @Override
    public void messageReceived(IoSession session, Object s) throws Exception {
        super.messageReceived(session, s);
        //接收
//        InkeMessage im=(InkeMessage)message;

        LogUtils.e("收到消息:"+s.toString());
        ToastUtils.showShort("客户端消息:"+s.toString()+":客户端IP："+session.getRemoteAddress());

        //发送给特定客户端
        SessionSendUtils.getIns().sendMsg("hi my is service",session);

        //发送
//        im.setName("客户端你好");
//        session.write("my is service ");
    }

    /**
     * 消息已送达在客户端
     * */
    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
        LogUtils.e("客户端已接收消息");
    }

    /***
     * 一个客户端关闭
     * */
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        LogUtils.e("客户端关闭");
        SessionSendUtils.getIns().removeIosession(session);
    }


    /***
     * 链接进入空闲状态
     * */
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
        LogUtils.e("链接空闲");
    }


    /**
     * 其他方法异常
     * */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
        LogUtils.e("其他方法异常");
    }
}
